//
//  ShoppingCarViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/30.
//

import UIKit
import MJRefresh
import SkeletonView
class CarDataList {
    /// 0：普通正常的商品  1: 秒杀  2：过期商品
    var type: NSInteger = 0
    var products: [ShoppingCarListModel] = []
    init() {
        
    }
}

class ShoppingCarViewController: BaseViewController {
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var pageNum = 1
    var bottomView: UIView!  //底部视图
    var allSelectBtn: UIButton!//全选按钮
    var editorBtn: UIButton!
    var confirmOrderBtn: LoaddingButton!//确认订单
    var amountToPriceLab: UILabel!//合计价格
    var dataList: [CarDataList] = []
    var timer: Timer!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("shopping_cart", comment: "购物车")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.createNaviBar()
        self.createBottomView()
        self.initTableView()
        self.setUpNoData()
        self.addPullRefreash()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    }
    
    private func createNaviBar() {
        editorBtn = UIButton()
        editorBtn.setup_titleLabel(text: MMLocalizedString("management", comment: "管理"))
        editorBtn.setTitle(MMLocalizedString("add_done", comment: "完成"), for: .selected)
        editorBtn.setup_titleColor(color: Theme.titleLabColor)
        editorBtn.setTitleColor(Theme.titleLabColor, for: .selected)
        editorBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        editorBtn.isSelected = false
        editorBtn.addTarget(self, action: #selector(editorBtnAntion), for: .touchUpInside)
        self.navBar.addSubview(editorBtn)
        
        editorBtn.titleLabel?.frame.size.width = 200
        editorBtn.titleLabel?.sizeToFit()
        let tempW = editorBtn.titleLabel?.frame.size.width ?? 0
        editorBtn.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.top.equalTo(IphoneTopArea)
            make.height.equalTo(44)
            make.width.equalTo(tempW + 16)
        }
    }
    
    private func initTableView() {
        self.tableView = BaseTableView.init(frame: CGRect(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight - TabbarHeight), style: .plain)
        self.tableView.backgroundColor = Theme.whiteColor
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        self.tableView.register(CarNormalSecCell.self, forCellReuseIdentifier: "CarNormalSecCell")
        self.tableView.register(CarTimerSecCell.self, forCellReuseIdentifier: "CarTimerSecCell")
        self.tableView.register(CarExpireSecCell.self, forCellReuseIdentifier: "CarExpireSecCell")
        self.tableView.register(SkeletonTableCell.self, forCellReuseIdentifier: "SkeletonTableCell")
        self.tableView.separatorStyle = .none
        self.tableView.estimatedRowHeight = 80
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.isSkeletonable = true
        self.view.addSubview(self.tableView)
        //self.addLoadMoreRefreash()
    }
    
    /// 合计
    private func createBottomView()  {
        self.bottomView = UIView(frame: CGRect(x: 0, y: kScreenHeight - TabbarHeight, width: kScreenWidth, height: TabbarHeight))
        self.bottomView.backgroundColor = .white
        self.view.addSubview(self.bottomView)
        
        //全选
        self.allSelectBtn = UIButton(frame: CGRect(x: 14, y: 0, width: 60, height: 50))
        self.allSelectBtn.setImage(UIImage(named: "icon_shopingcar_normal"), for: .normal)
        self.allSelectBtn.setImage(UIImage(named: "icon_shopingcar_selected"), for: .selected)
        self.allSelectBtn.setTitle(MMLocalizedString("check_all", comment: "  全选"), for: .normal)
        self.allSelectBtn.setTitleColor(Theme.titleLabColor, for: .normal)
        self.allSelectBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 13)
        self.allSelectBtn.addTarget(self, action: #selector(self.allSelectBtnAction), for: .touchUpInside)
        self.bottomView.addSubview(self.allSelectBtn)
        
        
        self.amountToPriceLab = UILabel()
        self.amountToPriceLab.textAlignment = .right
        self.amountToPriceLab.adjustsFontSizeToFitWidth = true
        self.amountToPriceLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 18)
        self.bottomView.addSubview(self.amountToPriceLab)
         
        self.amountToPriceLab.text = String(format: "%@%@%.2f", MMLocalizedString("all_price", comment: "总价："), XTManageCenter.currentSign(), 0)
        
        self.confirmOrderBtn = LoaddingButton(frame: CGRect(x: kScreenWidth - 138, y: 4, width: 120, height: 46))
        self.confirmOrderBtn.setup_titleLabel(text: MMLocalizedString("submit_order", comment: "结算"))
        self.confirmOrderBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: Theme.mainColor), for: .normal)
        self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: Theme.mainColorHighLightColor), for: .highlighted)
        self.confirmOrderBtn.isUserInteractionEnabled = true
        self.confirmOrderBtn.layer.cornerRadius = 8
        self.confirmOrderBtn.layer.masksToBounds = true
        self.confirmOrderBtn.setTitleColor(.white, for: .normal)
        self.confirmOrderBtn.addTarget(self, action: #selector(confirmOrderBtnAction), for: .touchUpInside)
        self.bottomView.addSubview(self.confirmOrderBtn)
        
        let lineView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0.5))
        lineView.backgroundColor = Theme.lineColor
        bottomView.addSubview(lineView)
        
        allSelectBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.top.equalTo(0)
            make.width.equalTo(60)
            make.height.equalTo(50)
        }
        let btnHeight: CGFloat = IphoneXMarginBottom > 1 ? 46 : 42
        confirmOrderBtn.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.top.equalTo(4)
            make.height.equalTo(btnHeight)
            make.width.equalTo(120)
        }
        
        amountToPriceLab.snp.makeConstraints { make in
            make.left.equalTo(allSelectBtn.snp.right).offset(10)
            make.top.equalTo(0)
            make.right.equalTo(confirmOrderBtn.snp.left).offset(-20)
            make.height.equalTo(50)
        }
    }
    
    
    //MARK: - 下拉刷新
    func addPullRefreash()  {
        weak var weakself = self
        self.tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself?.pageNum = 1
            weakself!.requestGetShoppingCartList(isMore: false, hudFlag: false)
        })
        self.tableView.showAnimatedSkeleton()
        self.requestGetShoppingCartList(isMore: false, hudFlag: false)
    }
    
    //MARK: - 上拉加载更多
//    private func addLoadMoreRefreash()  {
//        weak var weakself = self
//        self.tableView.mj_footer = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
//            weakself?.pageNum = weakself!.pageNum + 1
//            weakself?.requestGetShoppingCartList(isMore: true)
//            self.tableView.mj_footer.endRefreshing()
//        })
//    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: MMLocalizedString("check_other", comment: "去逛一逛")) {
            self.emptyViewBtnAction()
        }
        
        emptyView.actionBtnTitleColor = Theme.titleLabColor
        emptyView.actionBtnBorderColor = Theme.titleLabColor
        emptyView.actionBtnBorderWidth = 1
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -50
        emptyView.actionBtnBackGroundColor = UIColor.clear
        self.tableView.ly_emptyView = self.emptyView
    }
    
    @objc func emptyViewBtnAction(){
//        self.tableView.showAnimatedSkeleton(transition: SkeletonTransitionStyle.crossDissolve(1))
        self.navigationController?.popToRootViewController(animated: false)
        if let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController {
            tabbarVC.selectedIndex = 0
        }
    }
    
    /// 我的购物车列表
    func requestGetShoppingCartList(isMore: Bool, hudFlag: Bool) {
        if hudFlag {
            self.view.showLoadingHUDText(nil)
        }
        var param: [String: String] = [:]
        param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        param["pageNumber"] = "\(self.pageNum)"
        param["pageSize"] = "9999"
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getShoppingCartList(param: param), objectType: ShoppingCarModel.self) { [self] data in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.handleLoading()
            let resultObj = data as! ShoppingCarModel
            if resultObj.code == "1" {
                let tempList = resultObj.data ?? []
                //获取选中的skuids, 恢复默认选中的商品
                let selectSkuIds = self.getSelectProductSkuIds(isValid: false, idType: 0).components(separatedBy: ",")
                if selectSkuIds.count > 0 {
                    tempList.forEach { product in
                        if selectSkuIds.contains("\(product.skuId ?? 0)") {
                            product.isSelect = true
                        }else{
                            product.isSelect = false
                        }
                    }
                }
                self.dataList = self.handleResponseCarData(data: tempList)
                self.calculateTotalPrice()
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
            self.tableView.hideSkeleton(reloadDataAfter: true, transition: .none)
        } error: { err in
            self.tableView.hideSkeleton(reloadDataAfter: true, transition: .none)
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.makeToastBottom(message: err?.domain ?? MMLocalizedString("request_failed", comment: "请求失败，请稍候再试"))
        }
    }
    
    /// 对购物车数据做处理，分组（arr1普通商品， arr2秒杀商品， arr3过期商品）
    private func handleResponseCarData(data: [ShoppingCarListModel]) -> [CarDataList]{
        var arr1: [ShoppingCarListModel] = []
        var arr2: [ShoppingCarListModel] = []
        var arr3: [ShoppingCarListModel] = []
        _ = data.map { item in
            //修改商品数量时回调
            item.modifyBlock = {[weak self] num in
                self?.fetchModifyCartAddNum(skuId: item.skuId ?? 0, quantity: num)
            }
            
            //选中商品
            item.selectBlock = {[weak self] in
                item.isSelect = !item.isSelect
                self?.handleSelectProduct()
              
            }

            //下架、 售空、失效
            if item.isShelf == 0 ||
                item.availableStock == 0 ||
                item.isValid == false {
                arr3.append(item)
            }else if item.isLimitedTime == 1 {
                //秒杀商品
                arr2.append(item)
            }else {
                //普通正常商品
                arr1.append(item)
            }
        }
        
        //普通商品分组
        let tempList1 = CarDataList()
        tempList1.products = arr1
        tempList1.type = 0
        
        //秒杀商品分组
        let tempList2 = CarDataList()
        tempList2.products = arr2
        tempList2.type = 1
        
        //过期商品分组
        let tempList3 = CarDataList()
        tempList3.products = arr3
        tempList3.type = 2
        
        return [tempList1, tempList2, tempList3]
    }
    
    
    ///选中商品
    private func handleSelectProduct(){
        let tempList = self.dataList.flatMap{$0.products.map{$0}}
        let findObj = tempList.first { product in
            //有效商品，且未选中时
            if !(product.isShelf == 0 ||
                 product.availableStock == 0 ||
                 product.isValid == false) &&
                product.isSelect == false {
                return true
            }
            return false
        }
        if findObj != nil {
            //说明找到了一个未选中的有效商品
            self.allSelectBtn.isSelected = false
        }else{
            self.allSelectBtn.isSelected = true
        }
        self.calculateTotalPrice()
    }
    
    
    ///去计算价格
    private func calculateTotalPrice(){
        var totalPrice: Double = 0
        self.dataList.forEach { secList in
            _ = secList.products.map { product in
                if !(product.isShelf == 0 ||
                     product.availableStock == 0 ||
                     product.isValid == false) &&
                    product.isSelect == true {
                    //只计算有效价格
                    totalPrice = totalPrice + Double(product.quantity ?? 0) * (product.price ?? 0)
                }
            }
        }
        
        
        self.amountToPriceLab.text = String(format: "%@%@%@", MMLocalizedString("all_price", comment: "总价："), XTManageCenter.currentSign(), XTManageCenter.showPriceInComma(source: totalPrice.cleanZero))
        self.tableView.reloadData()
        self.tableView.hideSkeleton()
    }
    
    /// 修改购物数量车添加商品 addType 1：商品列表加入，2：购物车列表更改数量）
    func fetchModifyCartAddNum(skuId: Int,quantity: Int){
        self.view.showLoadingHUDText(nil)
        var param = NSMutableDictionary() as! [String: Any]
        param["skuId"] = "\(skuId)"
        param["quantity"] = "\(quantity)"
        param["addType"] = "2"
        if UserModule.shared.isLogined ?? false == false {  //未登录
            param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        }
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.cartDAddNum(param: param), objectType: AddShopingCartModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! AddShopingCartModel
            if resultObj.code == "1" {
                //let model = resultObj.data
                self.dataList.forEach { secList in
                    for product in secList.products {
                        if product.skuId ?? 0 == skuId {
                            product.quantity = quantity
                            break
                        }
                    }
                   
                }
                self.calculateTotalPrice()
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
                self.tableView.reloadData()
            }
        } error: { err in
            self.tableView.reloadData()
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    /// 编辑
    @objc func editorBtnAntion(){
        guard self.dataList.count > 0 else {
            return
        }
        self.editorBtn.isSelected = !self.editorBtn.isSelected
        if self.editorBtn.isSelected {
            //编辑中
            self.amountToPriceLab.isHidden = true
            self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: Theme.redColor), for: .normal)
            self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xE8181A, alpha: 0.8)), for: .highlighted)
            self.confirmOrderBtn.setup_titleLabel(text: MMLocalizedString("delete", comment: "删除"))
            self.tableView.reloadData() //为是隐藏加减按钮
        }else{
            //完成编辑
            self.amountToPriceLab.isHidden = false
            self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: Theme.mainColor), for: .normal)
            self.confirmOrderBtn.setBackgroundImage(UIImage.init(color: Theme.mainColorHighLightColor), for: .highlighted)
            self.confirmOrderBtn.setup_titleLabel(text: MMLocalizedString("submit_order", comment: "结算"))
            self.calculateTotalPrice()
        }
    }
    
    
    ///全选
    @objc func allSelectBtnAction(){
        guard self.dataList.count > 0 else {
            return
        }
        self.allSelectBtn.isSelected = !self.allSelectBtn.isSelected
        self.dataList.forEach { secList in
            secList.products.forEach { product in
                product.isSelect = self.allSelectBtn.isSelected
            }
        }
        self.calculateTotalPrice()
    }
 
    ///确认订单
    @objc func confirmOrderBtnAction() {
        if self.editorBtn.isSelected {
            XTAlertView.showAlertView(title: MMLocalizedString("hint", comment: "提示"), message: MMLocalizedString("car_del_product_tip", comment: "确定删除选中的商品吗？"), cancelButtonTitle: MMLocalizedString("my_reserver_cancel", comment: "取消"), otherButtonTitlesArr: [MMLocalizedString("my_reserver_confirm", comment: "确定")]) { alertView, buttonIndex in
                if buttonIndex == 1 {
                    //确定
                    self.handleDeleteProduct()
                }
            }
            return
        }
        if UserModule.shared.isLogined ?? false == false {
            XTManageCenter.shared.jumpToLoginView() //未登录
            return
        }
        self.handleCheckout()
    }
    
    ///结算
    private func handleCheckout(){
       
        let skuIds = self.getSelectProductSkuIds(isValid: true, idType: 1)
        let param: [String: String] = ["cartIds": skuIds]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.productOrder(param: param), objectType: PreviewProductOrderResModel.self) { data in
            let resultObj = data as! PreviewProductOrderResModel
            if resultObj.code == "1" {
                //成功
                let vc = ConfirmOrderViewController()
                vc.cartIds = self.getSelectProductSkuIds(isValid: true, idType: 1)
                vc.orderData = resultObj.data
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///获取skuID 移除时用到
    /// isValid: true 只获取有效商品的skuid  false 获取所有的skuid
    /// idType 0：取skuID (删除商品时用)  1：取id （结算时用）
    private func getSelectProductSkuIds(isValid: Bool, idType: NSInteger) -> String {
        var tempArray:[String] = []
        self.dataList.forEach { secList in
            if isValid {
                //选中且有效商品
                secList.products.forEach { product in
                    if !(product.isShelf == 0 ||
                         product.availableStock == 0 ||
                         product.isValid == false) &&
                        product.isSelect {
                        if idType == 0 {
                            tempArray.append("\(product.skuId ?? 0)")
                        }else{
                            tempArray.append("\(product.id ?? 0)")
                        }
                    }
                }
            }else{
                //选中所有商品，包括无效的
                secList.products.forEach { product in
                    if product.isSelect {
                        //选中的，且有效商品
                        if idType == 0 {
                            tempArray.append("\(product.skuId ?? 0)")
                        }else{
                            tempArray.append("\(product.id ?? 0)")
                        }
                    }
                }
            }
        }
        return tempArray.joined(separator: ",")
    }
    
    ///删除
    private func handleDeleteProduct(){
        var param:[String: String] = [:]
        if UserModule.shared.isLogined ?? false == false {  //未登录属于游客需要这个
            param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        }
        param["skuId"] = self.getSelectProductSkuIds(isValid: false, idType: 0) //获取所有选中的skuId
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.removeSingleCartGoods(param: param), objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                self.view.makeToast(message: MMLocalizedString("successfully_delete", comment: "删除成功"))
                self.dataList = self.dataList.map { secList in
                    let tempSec = secList
                    let tempArr = secList.products.filter{$0.isSelect == false}
                    tempSec.products = tempArr
                    return tempSec
                }
                self.tableView.reloadData()
                self.calculateTotalPrice()
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    //MARK: - Requset
    //订单详情
    func requestGetProductOrderDetail(){
        self.view.showLoadingHUDText(nil)
//        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.productOrderDetail(param: ["id": "\(self.id)"]), objectType: OrderInfoPreviewModel.self) { data in
//            self.view.handleLoading()
//            let resultObj = data as! OrderInfoPreviewModel
//            if resultObj.code == "1" {
//                self.infoModel = resultObj.data
//                self.obligationDealData()
//
//                //待付款时间到结束刷新数据
//                self.infoModel?.refreshDataBlock = { [weak self] in
//                    self?.requestGetProductOrderDetail()
//                }
//            }else{
//                self.view.makeToastBottom(message: resultObj.msg ?? "")
//            }
//            self.tabelView.reloadData()
//        } error: { err in
//            self.view.handleLoading()
//            self.view.makeToastBottom(message: err?.domain ?? "")
//        }
    }
}

extension ShoppingCarViewController: SkeletonTableViewDataSource, SkeletonTableViewDelegate {
    ///骨骼加载视图 -------
    func numSections(in collectionSkeletonView: UITableView) -> Int {
        return 1
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SkeletonTableCell", for: indexPath) as! SkeletonTableCell
        cell.clipsToBounds = true
        cell.selectionStyle = .none
        return cell
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
        return "SkeletonTableCell"
    }
    ///骨骼加载视图 -------//
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataList.count > section {
            let arr = self.dataList[section]
            if arr.products.count > 0 {
                return 1
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
   
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
            return IphoneXMarginBottom + 34
        }
        return 0.1
    }

  
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
   
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard self.dataList.count > indexPath.section else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "space", for: indexPath)
            return cell
        }
       
        let dataModel = self.dataList[indexPath.section]
        switch dataModel.type {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CarNormalSecCell", for: indexPath) as! CarNormalSecCell
                cell.editFlag = self.editorBtn.isSelected
                cell.setCarNormalSecCell(data: dataModel.products)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CarTimerSecCell", for: indexPath) as! CarTimerSecCell
                cell.editFlag = self.editorBtn.isSelected
                cell.setCarNormalSecCell(data: dataModel.products)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "CarExpireSecCell", for: indexPath) as! CarExpireSecCell
                cell.editFlag = self.editorBtn.isSelected
                cell.setCarExpireSecCell(data: dataModel.products)
                cell.clipsToBounds = true
                cell.selectionStyle = .none
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "space", for: indexPath)
                return cell
        }
    }
    
}


